package com.zjuee.web.basic.captcha.service;

import com.zjuee.base.bean.response.CommonResultCode;
import com.zjuee.base.exception.BaseException;
import com.zjuee.service.basic.captcha.service.CaptchaService;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;

/**
 * @author wu liang
 * @since 1.0
 */
@Slf4j
public class CaptchaServiceFactory {


    /**
     * 根据验证码类型 获取对应的service
     */
    public static CaptchaService getInstance(String type) {
        CaptchaService ret = instances.get(type);
        if (ret == null) {
            throw new BaseException(CommonResultCode.ILLEGAL_INPUT, "无效的验证码类型");
        }
        return ret;
    }

    private static final Map<String, CaptchaService> instances = new HashMap();
    // 初始化时 加载所有接口的实现类 加入到map中
    static {
        ServiceLoader<CaptchaService> services = ServiceLoader.load(CaptchaService.class);
        for (CaptchaService item : services) {
            instances.put(item.captchaType(), item);
        }
    }
}
